package top.wshape1.rpc.provider.service;

import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.common.entity.ServiceMeta;
import top.wshape1.rpc.common.constant.RoleType;
import top.wshape1.rpc.registry.RpcRegistry;
import top.wshape1.rpc.registry.RpcRegistryFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Wshape1
 * @version 1.0
 * @description 服务接口工厂
 * @since 2024-02-02
 */

@Slf4j
public class RpcServiceFactory {

    /**
     * 本机提供的服务接口集合
     * serviceClass -> serviceImplementation
     */
    private static final Map<Class<?>, Object> SERVICE_MAP = new ConcurrentHashMap<>();

    public static <T> T getService(Class<T> clazz) {
        return clazz.cast(SERVICE_MAP.get(clazz));
    }

    public static Map<Class<?>, Object> getServiceMap() {
        return SERVICE_MAP;
    }

    /**
     * 注册服务接口到本地和注册中心
     *
     * @param serviceInterfaceClass 服务接口
     * @param serviceImplementation 服务实现
     * @param <T> 服务对象的类型
     */
    public static <T> void registryService(Class<T> serviceInterfaceClass, T serviceImplementation) {
        ServiceMeta serviceMeta = ServiceMeta.selfServiceMeta(serviceInterfaceClass.getName(), RoleType.provider);
        RpcRegistryFactory.getRegistry().register(serviceMeta);
        SERVICE_MAP.putIfAbsent(serviceInterfaceClass, serviceImplementation);
    }

    /**
     *
     */
    public static void unregisterAllService() {
        RpcRegistry registry = RpcRegistryFactory.getRegistry();
        ServiceMeta serviceMeta = ServiceMeta.selfServiceMeta(null, RoleType.provider);
        RpcServiceFactory.getServiceMap().forEach((serviceClass, serviceImpl) -> {
            serviceMeta.setServiceName(serviceClass.getName());
            registry.unregister(serviceMeta);
        });
        SERVICE_MAP.clear();
    }

}
